package com.ebupt.migu.music.bannertwo.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ebupt.migu.mediadata.pojo.MediaActivity;
import com.ebupt.migu.music.bannertwo.entity.BannerTwoCheck;
import com.ebupt.migu.music.bannertwo.entity.BannerTwoDetail;
import com.ebupt.migu.music.bannertwo.entity.BannerTwoInfo;
import com.ebupt.migu.music.bannertwo.entity.BannerTwoProperty;
import com.ebupt.migu.music.bannertwo.mapper.BannerTwoCheckMapper;
import com.ebupt.migu.music.bannertwo.mapper.BannerTwoDetailMapper;
import com.ebupt.migu.music.bannertwo.mapper.BannerTwoInfoMapper;
import com.ebupt.migu.music.bannertwo.service.IBannerTwoInfoService;
import com.ebupt.migu.music.common.entity.ResultObject;
import com.ebupt.migu.music.bannertwo.enums.ConditionEnum;
import com.ebupt.migu.music.bannertwo.enums.FropertyEnum;
import com.ebupt.migu.music.bannertwo.enums.IdentifierEnum;
import com.ebupt.migu.music.media.entity.MediaCheck;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class BannerTwoInfoServiceImpl extends ServiceImpl<BannerTwoInfoMapper, BannerTwoInfo> implements IBannerTwoInfoService {

	@Autowired
	private BannerTwoInfoMapper bannerTwoInfoMapper;
	@Autowired
	private BannerTwoDetailMapper bannerTwoDetailMapper;
	@Autowired
	private BannerTwoCheckMapper checkMapper;
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(BannerTwoInfo bannerTwoInfo, List<BannerTwoDetail> bannerTwoDetailList) {

		if ("1".equals(bannerTwoInfo.getExecutionType())) {
			bannerTwoInfo.setExecutionStatus("1");
		} else {
			if(DateUtil.date().isBefore(DateUtil.date(bannerTwoInfo.getStartTime()))){
				bannerTwoInfo.setExecutionStatus("4");
			}else {
				bannerTwoInfo.setExecutionStatus("3");
			}
		}
		List<BannerTwoInfo> list = this.list();
		if(null!=list&& !list.isEmpty()){
			list.forEach(obj->{
				obj.setPriority(obj.getPriority()+1);
			});
			boolean b = this.updateBatchById(list);
			if(!b){
				throw new RuntimeException("保存失败");
			}
		}
		bannerTwoInfo.setPriority(1);//set(1)
		bannerTwoInfoMapper.insert(bannerTwoInfo);
		if(bannerTwoDetailList!=null && bannerTwoDetailList.size()>0) {
			for(BannerTwoDetail entity:bannerTwoDetailList) {
				//外键设置
				entity.setBannerId(bannerTwoInfo.getId());
				bannerTwoDetailMapper.insert(entity);
			}
		}
		if ("1".equals(bannerTwoInfo.getExecutionType())) {
			//创建审核
			BannerTwoCheck check = new BannerTwoCheck();
			check.setApproverName(bannerTwoInfo.getApproverName());
			check.setBannerTwoId(bannerTwoInfo.getId());
			check.setBannerTwoName(bannerTwoInfo.getBannerName());
			check.setCreateTime(bannerTwoInfo.getCreateTime());
			check.setState(0);
			check.setDeleteType(0);
			check.setApproverId(bannerTwoInfo.getApproverId());
			check.setProposer(bannerTwoInfo.getCreatorName());
			check.setDepartment(bannerTwoInfo.getCreatorDepartment());
			checkMapper.insert(check);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(BannerTwoInfo bannerTwoInfo,List<BannerTwoDetail> bannerTwoDetailList) {
		if ("1".equals(bannerTwoInfo.getExecutionType())) {
			bannerTwoInfo.setExecutionStatus("1");
		} else {
			if(DateUtil.date().isBefore(DateUtil.date(bannerTwoInfo.getStartTime()))){
				bannerTwoInfo.setExecutionStatus("4");
			}else {
				bannerTwoInfo.setExecutionStatus("3");
			}
		}
		BannerTwoCheck check = checkMapper.selectOne(new QueryWrapper<BannerTwoCheck>().lambda().eq(BannerTwoCheck::getBannerTwoId, bannerTwoInfo.getId()));
//		if((null!=check&&2==check.getState())||"5".equals(bannerTwoInfo.getExecutionStatus())||"7".equals(bannerTwoInfo.getExecutionStatus())){
//			checkMapper.update(new UpdateWrapper<BannerTwoCheck>().lambda().eq(BannerTwoCheck::getBannerTwoId,bannerTwoInfo.getId()).set(BannerTwoCheck::getState,0));
//		}
		if(null!=check){
			checkMapper.update(new UpdateWrapper<BannerTwoCheck>().lambda().eq(BannerTwoCheck::getBannerTwoId,bannerTwoInfo.getId()).set(BannerTwoCheck::getState,0).set(BannerTwoCheck::getDeleteType,0));
		}
       if(check==null&&"1".equals(bannerTwoInfo.getExecutionType())){
		   BannerTwoCheck check1 = new BannerTwoCheck();
		   check1.setApproverName(bannerTwoInfo.getApproverName());
		   check1.setBannerTwoId(bannerTwoInfo.getId());
		   check1.setBannerTwoName(bannerTwoInfo.getBannerName());
		   check1.setCreateTime(bannerTwoInfo.getCreateTime());
		   check1.setState(0);
		   check1.setDeleteType(0);
		   check1.setApproverId(bannerTwoInfo.getApproverId());
		   check1.setProposer(bannerTwoInfo.getCreatorName());
		   check1.setDepartment(bannerTwoInfo.getCreatorDepartment());
		   checkMapper.insert(check1);
	   }

		bannerTwoInfoMapper.updateById(bannerTwoInfo);
		
		//1.先删除子表数据
		bannerTwoDetailMapper.deleteByMainId(bannerTwoInfo.getId());
		
		//2.子表数据重新插入
		if(bannerTwoDetailList!=null && bannerTwoDetailList.size()>0) {
			for(BannerTwoDetail entity:bannerTwoDetailList) {
				//外键设置
				entity.setBannerId(bannerTwoInfo.getId());
				bannerTwoDetailMapper.insert(entity);
			}
		}

	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(Map<String, Object> params) {
		String bannerid = (String) params.get("id");
		BannerTwoInfo info = bannerTwoInfoMapper.selectOne(new QueryWrapper<BannerTwoInfo>().lambda().eq(BannerTwoInfo::getId, bannerid));
		bannerTwoDetailMapper.deleteByMainId(bannerid);
		bannerTwoInfoMapper.deleteById(bannerid);
		//删除数据，需要重排活动优先级
		Map<String, Object> map = new HashMap<>();
		map.put("type", "3");
        map.put("priority", info.getPriority());
		priority(map);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			bannerTwoDetailMapper.deleteByMainId(id.toString());
			bannerTwoInfoMapper.deleteById(id);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public ResultObject priority(Map<String, Object> params) {
		ResultObject resultObject = new ResultObject<>();
//		List<BannerTwoInfo> activityList = bannerTwoInfoMapper.selectList(new QueryWrapper<MediaActivity>().lambda()
//				.eq(BannerTwoInfo::getDisplayType, params.get("displayType"))
//				.eq(BannerTwoInfo::getVisitPoint, params.get("visitPoint"))
//		);
		List<BannerTwoInfo> bannerlist=this.list();
		//按照优先级排序
		bannerlist.sort(Comparator.comparing(BannerTwoInfo::getPriority));
		int cur = Integer.parseInt(params.get("priority").toString());
		int tmp;
		//升序情况，交换当前位置前一个数据的优先级
		if ("1".equals(params.get("type"))) {
			if (cur == 1) {
				resultObject.setCode("-1");
				resultObject.setMsg("已是最高优先级");
				return resultObject;
			}
			for (int i = 0; i < bannerlist.size(); i++) {
				if (cur == bannerlist.get(i).getPriority()) {
					tmp = cur;
					bannerlist.get(i).setPriority(bannerlist.get(i - 1).getPriority());
					bannerlist.get(i - 1).setPriority(tmp);
				}
			}
		}
		//降序情况，交换当前位置后一个数据的优先级
		if ("2".equals(params.get("type"))) {
			if (cur >= bannerlist.size()) {
				resultObject.setCode("-1");
				resultObject.setMsg("已是最低优先级");
				return resultObject;
			}
			for (int i = 0; i < bannerlist.size() - 1; i++) {
				if (cur == bannerlist.get(i).getPriority()) {
					tmp = cur;
					bannerlist.get(i).setPriority(bannerlist.get(i + 1).getPriority());
					bannerlist.get(i + 1).setPriority(tmp);
				}
			}
		}
		//重置排序
		if ("3".equals(params.get("type"))) {
			for (int i = 0; i < bannerlist.size(); i++) {
				bannerlist.get(i).setPriority(i + 1);
			}
		}
		bannerlist.forEach(e -> bannerTwoInfoMapper.updateById(e));
		resultObject.setCode("0000");
		resultObject.setMsg("成功");
		return resultObject;
	}

	@Override
	public ResultObject getConditions() {
		ResultObject resultObject = new ResultObject();
		List<BannerTwoProperty> properties = bannerTwoInfoMapper.selectPropertyList();
		Map<Integer, List<BannerTwoProperty>> PropertyListMap = properties.stream().collect(Collectors.groupingBy(BannerTwoProperty::getPropertyCode));
		ArrayList<HashMap> list = new ArrayList<>();


		for (Map.Entry<Integer, List<BannerTwoProperty>> listEntry : PropertyListMap.entrySet()) {
			FropertyEnum fropertyEnum = FropertyEnum.get(listEntry.getKey());
			HashMap resultMap = new HashMap<>();
			resultMap.put("PropertyCode", listEntry.getKey());
			resultMap.put("PropertyName", fropertyEnum.getName());
			List<HashMap> categorys = listEntry.getValue().stream().map(property -> {
				ConditionEnum conditionEnum = ConditionEnum.get(property.getPropertyCode(), property.getConditionKey());
				HashMap<String, Object> map = new HashMap<>(3);
				map.put("ConditionCode", conditionEnum.getConditionKey());
				map.put("ConditionValue", conditionEnum.getValue());
				map.put("ConditionName", conditionEnum.getName());
				map.put("ConditionTip", property.getConditionTip());

				if (property.getRelations() != null) {
					List<HashMap> relations = Arrays.stream(property.getRelations().split(",")).map(s -> {
						HashMap imap = new HashMap<>();
						imap.put("Relation", s);
						imap.put("RelationValue", IdentifierEnum.getNameByCode(Integer.parseInt(s)));
						return imap;
					}).collect(Collectors.toList());
					map.put("relations", relations);
				}
				return map;
			}).collect(Collectors.toList());

			resultMap.put("categorys", categorys);
			list.add(resultMap);
		}
		resultObject.setCode("0000");
		resultObject.setMsg("成功");
		resultObject.setData(list);
		return resultObject;	}

}
